<!DOCTYPE html>
<html>
	<head>
		<meta name="viewport" content="width=320,user-scalable=no" />
    	<meta charset="utf-8" />
		<title></title>
		<style type="text/css">
			*{margin:0;padding:0;}
		</style>
	</head>
	<body>
		<canvas id="canvas"></canvas>
	</body>
</html>
<script type="text/javascript">
	
	var Game = function(){
		this.canvas = document.getElementById("canvas"),
		this.context = this.canvas.getContext("2d"),
		
		this.canvas.width = 300;
		this.canvas.height = 300;
		this.canvas.style.background = "#f0f0f0";
		
		this.fps;							//用于获取频率
		this.lastFramTime = 0;				//用于更新频率
		
		this.ren = new Image();				//------用于加载人的图片
		
		this.renSprite = [					//---------用于精灵动画{-{-{-{-{-{-举个栗子-}-}-}-}-}-}
			{left:0,top:0,width:200,height:200,x:0,y:0},
			{left:200,top:0,width:200,height:200,x:0,y:0},
			{left:400,top:0,width:200,height:200,x:0,y:0},
			{left:600,top:0,width:200,height:200,x:0,y:0}
		];
		this.sprites = [];
		this.hOffset = 0;      //精灵的水平偏移量
	}
	Game.prototype = {					
		draw : function(now){		//------------------绘制主程序-----------------------【3-3】
			suchen.undateSprites();
			suchen.drawSprites();
		},
		undateSprites : function(now){		//----------------更新全部精灵-------------【4-1】
//			console.log("----------");
			var sprite;
			for(var i = 0; i < this.sprites.length; i++){
				sprite = this.sprites[i];
				/*判断精灵是否可以显示  和  是否在屏幕内*/
				if(sprite.visible && this.isSpriteInView(sprite)){
					sprite.update(now,
								this.fps,
								this.context,
								this.lastFramTime);
				}
			}
		},
		drawSprites : function(){		//-----------------绘制精灵--------------------【4-2】
			var sprite;
			for(var i=0;i<this.sprites.length;i++){
				sprite = this.sprites[i];
				if(sprite.visible && this.isSpriteInView(sprite)){
					this.context.translate(-sprite.hOffset,0);
					sprite.draw(this.context);
					this.context.translate(sprite.hOffset,0);
				}
			}
		},
		isSpriteInView : function(sprite){		//--------------判断精灵是否在画布内--------【5】
			return sprite.left + sprite.width > sprite.hOffset
					&& sprite.left < sprite.hOffset + this.canvas.width;
		},
		getFps : function(now){				//------------获取频率*---------------【3-2】
			var fps = 1 / (now - this.lastFramTime) * 1000;
			return fps;
		},
		clearCanvas : function(){		//-----------------清除画布---------------【3-1】
			suchen.context.clearRect(0,0,this.canvas.width,this.canvas.height);
		},
		animate : function(now){		//----------开始运行-------------------【2】
			suchen.clearCanvas();
			suchen.getFps(now);
			suchen.draw(now);
			suchen.lastFramTime = now;
			requestAnimationFrame(suchen.animate);	//循环运行
		},
		init : function(){			//--------------初始化-----------------------【1】
			this.ren.src = "img/sprite.png";
			this.ren.onload = function(){
				suchen.animate();
			}
		},
	}
	
	
	var suchen = new Game();
	suchen.init();
</script>